package com.sun;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class CBC {

    private static final String key = "1111111111111111";
    private static final String initVector = "1111111111111111";

    public static String encrypt(String value) {
        try {
            //Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            //Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            Cipher cipher = Cipher.getInstance("AES/CBC");
            int blockSize = cipher.getBlockSize();
            int plaintextLength = value.getBytes().length;
            if (plaintextLength % blockSize != 0){
                plaintextLength = plaintextLength +(blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(value.getBytes(StandardCharsets.UTF_8),0,plaintext,0,value.length());

            cipher.init(Cipher.ENCRYPT_MODE,
                    new SecretKeySpec(key.getBytes("UTF-8"), "AES"),
                    new IvParameterSpec(initVector.getBytes("UTF-8")));
            byte[] encrypted = cipher.doFinal(plaintext);
            //byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            //Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec,iv);
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] decode = decoder.decode(encrypted);
            byte[] original = cipher.doFinal(decode);


            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String originalString = "talent";
        System.out.println("Original String to encrypt - " + originalString);
        String encryptedString = encrypt(originalString);
        System.out.println("Encrypted String - " + encryptedString);
        String decryptedString = decrypt(encryptedString);
        //String decryptedString = decrypt("i9QU1XFRmbvWNXH4hsOWUw==");
        System.out.println("After decryption - " + decryptedString);
    }

}


